import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import { message } from 'ant-design-vue'
import { setCookie } from '@/utils/base'
// 获取当前时间
// village->大写  VILLAGE->小写
const AUTH_TOKEN_KEY = 'DA_YU_AUTH_TOKEN'
let hasShownLoginError = false // 是否已经显示过登录错误提示
export const saveAuthToken = (token, rememberMe = true) => {
  setCookie(AUTH_TOKEN_KEY, token)
}

export const getAuthToken = () => {
  return Cookies.get(AUTH_TOKEN_KEY) || ''
}

export const removeAuthToken = () => {
  Cookies.remove(AUTH_TOKEN_KEY)
}

const http = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL
})
// 请求拦截器   发送请求之前
http.interceptors.request.use((config) => {
  if (config.url && !config.url.match(/ajaxLogin/)) {
    config.headers['Authorization'] = `${getAuthToken()}`
  }
  return config
})
// 响应拦截器
http.interceptors.response.use(async (response) => {
  const { data } = response
  if (data.code === 401) {
    removeAuthToken()
    router.replace('/login').then()
    return Promise.reject(new Error('登录失效，请重新登录'))
  }
  if (data.code !== 200) {
    if (!hasShownLoginError) {
      message.error(data.msg)
      hasShownLoginError = true
    }
  }
  return Promise.resolve(response.data)
}),
  (error) => {
    return Promise.reject(error)
  }

export default http
